/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.fastagenerator.fastagrabber;

import com.compomics.fastagenerator.fastagrabber.consoleformatter.Percent;
import com.compomics.fastagenerator.fastagrabber.consoleformatter.Spinner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 *
 * @author Kenneth
 */
public class FastaFileGrabber {

    private FileWriter fstream;
    private ArrayList<String> fastaAsList;
    private List<String> chars = new ArrayList<String>();
    private String sequenceHeader;
    private static FastaFileGrabber grabber;
    private static FastaComposer composer;
    private static Spinner formatter;
    //LAST ACCESSION IN UNIPROT = 
    private static int first = 6647645;
    //FIRST ACCESSION IN UNIPROT = 
    private static int last = 121939825;
    private Thread spinningThread;

    /*G - Glycine (Gly)
     P - Proline (Pro)
     A - Alanine (Ala)
     V - Valine (Val)
     L - Leucine (Leu)
     I - Isoleucine (Ile)
     M - Methionine (Met)
     C - Cysteine (Cys)
     F - Phenylalanine (Phe)
     Y - Tyrosine (Tyr)
     W - Tryptophan (Trp)
     H - Histidine (His)
     K - Lysine (Lys)
     R - Arginine (Arg)
     Q - Glutamine (Gln)
     N - Asparagine (Asn)
     E - Glutamic Acid (Glu)
     D - Aspartic Acid (Asp)
     S - Serine (Ser)
     T - Threonine (Thr)*/
    {
        chars.add("P");
        chars.add("V");
        chars.add("L");
        chars.add("I");
        chars.add("M");
        chars.add("F");
        chars.add("Y");
        chars.add("W");
        chars.add("H");
        chars.add("K");
        chars.add("R");
        chars.add("Q");
        chars.add("E");
        chars.add("D");
        chars.add("S");
        chars.add("R");
    }

    private FastaFileGrabber() {
    }

    public static FastaFileGrabber getInstance(File outputFile) throws IOException {
        composer = FastaComposer.getInstance(outputFile);
        try {
            formatter = new Spinner();
        } catch (Exception ex) {
            // System.out.println(ex.getMessage());
        }
        if (grabber == null) {
            grabber = new FastaFileGrabber();
        }
        return grabber;
    }

    public void generateFastaNumber(int sequences) throws IOException {
        try {
            System.out.println("");
            Random randomGenerator = new Random();
            int i = 0;
            Percent percent = new Percent(sequences);
            percent.setPrefix("Retrieving sequences : ");
            while (i < sequences) {
                int randomInt = first + randomGenerator.nextInt(last - first);
                if (getFasta(randomInt)) {
                    composer.writeToFasta(fastaAsList);
                    fastaAsList.clear();
                    i++;
                    percent.setSuffix("[" + i + "/" + sequences + "]");
                    percent.increasePercent(1);
                }
            }
        } catch (Exception e) {
        } finally {
            composer.finalize();
        }
    }

    public boolean evaluateNucleotides(String line) {

        String[] lineChars = line.split("");

        int nucleotide = 0;
        int i = 0;
        while (i < lineChars.length) {
            String positionChar = lineChars[i];
            i++;
            if (chars.contains(positionChar)) {
                nucleotide++;
            }
            if (nucleotide > 10) {
                return true;
            }

        }
        return false;
    }

    public boolean getFasta(int fastaNumber) {
        try {
            URL tariff = new URL("http://www.ncbi.nlm.nih.gov/sviewer/viewer.fcgi?tool=portal&sendto=on&log$=seqview&db=protein&dopt=fasta&val=" + fastaNumber);
            URLConnection c = tariff.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
            String line;
            fastaAsList = new ArrayList<String>();
            boolean proteinSequence = false;
            String separator = " " + System.getProperty("line.separator");


            while ((line = br.readLine()) != null) {
                if (line.contains(">")) {
                    sequenceHeader = separator + line + separator;
                    fastaAsList.add(sequenceHeader);
                } else {
                    if (evaluateNucleotides(line)) {
                        fastaAsList.add(line);
                        proteinSequence = true;
                    }
                }
            }
            return proteinSequence;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return false;
    }
}
